package com.gitee.gen.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitee.gen.common.Action;
import com.gitee.gen.common.Result;
import com.gitee.gen.dto.UserDto;
import com.gitee.gen.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * @ClassName UserController
 * @Description: TODO
 * @author: xujc04
 * @date: 2022年02月24日 16:14
 */

@RestController
@RequestMapping("user")
public class UserController {

    @Value("${auth.username}")
    private String username ;

    @Value("${auth.password}")
    private String password ;

    @GetMapping("/getRandCode/{paramCode}")
    public Result getRandCode(@PathVariable("paramCode") String paramCode) {
        try {
            System.out.println("-----------------"  + paramCode);
            String randomCode = RandomUtil.randomString(CustomUtil.BASE_CHECK_CODES,4);
            String lowerCaseCode = randomCode.toLowerCase();
            String realKey = MD5Util.MD5Encode(lowerCaseCode+paramCode, "utf-8");

           // redisUtil.set(realKey, lowerCaseCode, 60);

            String base64 = RandImageUtil.generate(randomCode);

            return Action.ok(base64) ;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Action.err("验证码生成错误") ;
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {
        /*String captcha = userDto.getCaptcha();
        if(captcha==null){
           return Action.err("验证码无效");
        }

        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha+userDto.getCheckKey(), "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
            return Action.err("验证码错误");
        }*/

        if (username.equals(userDto.getUsername()) &&
            password.equals(userDto.getPassword())) {

            // 生成token
            String token = JwtUtil.sign(userDto.getUsername());
//            // 设置token缓存有效时间
//            redisUtil.set(CustomUtil.PREFIX_USER_TOKEN + token, token);
//            redisUtil.expire(CustomUtil.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

            System.out.println("token::" +  token );
            JSONObject json = new JSONObject();
            json.put("token" , token) ;
            return Action.ok(json) ;
        }
        return Action.err("用户名或密码错误") ;
    }


    @GetMapping("/info")
    public Result getUserInfo(@RequestParam("token") String token) {
     //   Object cacheToken = redisUtil.get(CustomUtil.PREFIX_USER_TOKEN + token) ;
        String username = JwtUtil.getUsername(token) ;
      //  System.out.println("username::" +  username );  // 超时后，获取不到username， 导致后面无法延期
        if (!StringUtils.isEmpty(username)) {
            if (!JwtUtil.verify(token, username)) { // 延期有BUG 。username获取不到
                String token1 = JwtUtil.sign(username);
            }
            JSONObject json = new JSONObject();
            json.put("name", "admin");
            json.put("avatar", "admin_avatar");
            json.put("code", 0);
            return Action.ok(json);
        }
        return Action.err("未登录或登录超时，请登录") ;
    }

    @PostMapping("/logout")
    public Result logOut(@RequestParam("token") String token) {
        System.out.println("------------退出成功----删除key-----begin-------" + token);
        //redisUtil.del(CustomUtil.PREFIX_USER_TOKEN + token);
        //System.out.println(redisUtil.get(CustomUtil.PREFIX_USER_TOKEN + token) );
        System.out.println("------------退出成功----删除key-----end-------");
        return Action.ok("退出成功") ;
    }
}
